<template>
  <div class="warp">
    <div class="title-box">用户信息</div>
    <div class="filter-box">
      <el-form ref="filterFormRef" :inline="true" :model="form" label-width="auto">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="form.username" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="年龄:" prop="age">
          <el-input v-model="form.age" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择" clearable>
            <el-option v-for="sex in sexOptions" :key="sex.id" :label="sex.label" :value="sex.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色:" prop="role">
          <el-select v-model="form.role" placeholder="请选择" clearable>
            <el-option v-for="role in roleOptions" :key="role.id" :label="role.label" :value="role.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期：" prop="createdAt">
          <el-date-picker
            v-model="form.createdAt"
            type="date"
            placeholder="请选择"
            clearable
          />
        </el-form-item>
      </el-form>
      <div class="btn-group">
        <el-button type="primary" :icon="Search" @click="searchHandle"
          >搜索</el-button
        >
        <el-button type="primary" :icon="Pointer" @click="resetFilterForm"
          >重置</el-button
        >
        <el-button type="primary" :icon="Plus" plain @click="addHandle"
          >新增用户</el-button
        >
      </div>
    </div>

    <!-- ================================================= -->
    <div class="table-box">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column fixed type="index" label="序号" width="80"/>
        <el-table-column prop="username" label="用户名" width="100" />
        <el-table-column prop="password" label="密码" width="100" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="sexTxt" label="性别" width="80" />
        <el-table-column prop="roleTxt" label="角色" width="100" />
        <el-table-column label="创建日期" width="200">
          <template #default="scope">{{ scope.row.createdAt }}</template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="userid" label="用户id" width="150" show-overflow-tooltip />
        <el-table-column prop="photo" label="头像" width="150"  show-overflow-tooltip />
        <el-table-column label="修改日期" width="200">
          <template #default="scope">{{ scope.row.updatedAt }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="Operations" min-width="120">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="editHandle(scope.row)"
              >编辑</el-button
            >
            <el-button
              link
              type="danger"
              size="small"
              @click="delHandle(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- ==================================== -->
    <div class="pagination-box">
      <el-pagination
        background
        layout="total, prev, pager, next, sizes"
        :total="total"
        :hide-on-single-page="!true"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!-- 添加修改对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="`${dialogFormTitle}用户`"
    width="700"
  >
    <el-form ref="ruleFormRef" :model="dialogForm" :rules="rules" label-width="120px" class="user-dialog-form">
      <el-form-item label="用户名:" prop="username">
        <el-input :disabled="dialogFormTitle == '编辑'" v-model="dialogForm.username" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="dialogForm.password" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="手机号:" prop="phone">
        <el-input v-model="dialogForm.phone" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="年龄:" prop="age">
        <el-input v-model="dialogForm.age" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="性别:" prop="sex">
        <el-select v-model="dialogForm.sex" placeholder="请选择" clearable>
          <el-option v-for="sex in sexOptions" :key="sex.id" :label="sex.label" :value="sex.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="角色:" prop="role">
        <el-select v-model="dialogForm.role" placeholder="请选择" clearable>
          <el-option v-for="role in roleOptions" :key="role.id" :label="role.label" :value="role.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="头像:" prop="photo">
        <el-input v-model="dialogForm.photo" type="textarea" :rows="4" placeholder="请输入头像url" clearable />
      </el-form-item>
      <el-form-item v-if="dialogFormTitle == '新增'" label="创建日期：" prop="createdAt">
        <el-date-picker
          v-model="dialogForm.createdAt"
          type="date"
          placeholder="请选择"
          clearable
        />
      </el-form-item>
      <el-form-item v-else label="修改日期：" prop="updatedAt">
        <el-date-picker
          v-model="dialogForm.updatedAt"
          type="date"
          placeholder="请选择"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelHandle">取消</el-button>
        <el-button type="primary" @click="saveHandle">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="user">
import { ref, reactive } from "vue";
import { Search, Plus, Delete, Edit, Upload, Pointer } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/user";
import { useMessage } from "@/hooks/message";
import {getUserListApi,  addUserApi, updateUserApi, delUserApi, getRoleOptionApi, getSexOptionApi} from '@/api/user';
import moment from 'moment';

const message = useMessage();
const userStore = useUserStore();
const page = ref(1)
const pagesize = ref(10)
const total = ref(0)
const filterFormRef = ref(null)
const ruleFormRef = ref(null)

const form = reactive({
  username: "",
  age: "",
  sex: "",
  role: "",
  createdAt: "",
});

const tableData = ref([])

const searchHandle = () => {
  getUserList()
};

const resetFilterForm = () => {
  filterFormRef.value.resetFields()
}

const addHandle = () => {
  // console.log("add!");
  dialogFormVisible.value = true;
  dialogFormTitle.value = "新增";
};

// 获取角色options
const roleOptions = ref({})
getRoleOptionApi().then(res => {
  roleOptions.value = res.data
})

// 获取性别options
const sexOptions = ref({})
getSexOptionApi().then(res => {
  sexOptions.value = res.data
})

// 查询列表
const getUserList = (data = {}) => {
  data = {page: page.value, pagesize: pagesize.value, ...form }
  getUserListApi(data).then(res => {
    tableData.value = res.data.map(row => {
      row.sexTxt = sexOptions.value.find(val => val.id == row.sex)?.label
      row.roleTxt = roleOptions.value.find(val => val.id == row.role)?.label
      row.createdAt = moment(res.createdAt).format('YYYY-MM-DD HH:mm:ss')
      row.updatedAt = moment(res.updatedAt).format('YYYY-MM-DD HH:mm:ss')
      return row
    })
    // console.log(tableData.value);
    
    total.value = res.total
    
  })
}
getUserList()

const editHandle = (option) => {
  console.log(option);
  dialogForm = option
  dialogFormVisible.value = true;
  dialogFormTitle.value = "编辑";
};

const delHandle = (option) => {
  delUserApi(option.userid).then(res => {
    getUserList()
    message.success(res.msg)
  }) 
};

const handleSizeChange = (val) => {
  console.log(`${val} items per page`);
  pagesize.value = val
  getUserList()
};
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
  page.value = val
  getUserList()
};

const dialogFormVisible = ref(false);
let dialogFormTitle = ref('');

let dialogForm = reactive({
  username: "",
  password: '',
  phone: '',
  age: "",
  sex: "",
  role: "",
  photo: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2025%2F0225%2F55e11aebj00ss7wp00032d000sg00sgg.jpg&thumbnail=660x2147483647&quality=80&type=jpg',
  createdAt: "",
  updatedAt: "",
});

const rules = reactive({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { required: true, pattern : /^1[3-9]\d{9}$/, message: '手机号格式不对', trigger: ['blur', 'change'] },
  ],
  role: [
    { required: true, message: '角色不能为空', trigger: ['blur', 'change'] },
  ],
  
})

const cancelHandle = () => {
  ruleFormRef.value.resetFields()
  dialogFormVisible.value = false;
};
const saveHandle = async() => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      let addOrUpdate;
      if (dialogFormTitle.value == '新增') {
        addOrUpdate = addUserApi
        delete dialogForm.userid
        delete dialogForm._id
      } else {
        addOrUpdate = updateUserApi
      }
      
      addOrUpdate(dialogForm).then(res => {
        if (res.code == 200) {
          cancelHandle();
          getUserList()
          message.success(res.msg)
        }else {
          // message.error(res.msg)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
};
</script>

<style lang="less" scoped>
.warp {
}

.title-box {
  padding: 20px;
  font-size: 20px;
  font-weight: bold;
}

.filter-box {
  background-color: #fff;
  padding: 20px;
  .el-input {
    --el-input-width: 220px;
  }

  .el-select {
    --el-select-width: 220px;
  }
  .btn-group {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}

.table-box {
  background-color: #fff;
  margin-top: 10px;
  padding: 20px;
}

.pagination-box {
  background-color: #fff;
  padding: 20px;
  display: flex;
  justify-content: center;
}

.user-dialog-form {
  .el-input {
    --el-input-width: 500px;
  }

  .el-select {
    --el-select-width: 500px;
  }

  .el-textarea {
    width: 500px;
  }
}
</style>
